package com.wcl.demo.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.wcl.demo.R;
import com.wcl.demo.db.AroundHelper;
import com.wcl.demo.model.entity.AroundInfor;
import com.wcl.demo.ui.fragment.QuitFragment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by dllo on 15/11/27.
 */
public class AroundActivity extends FragmentActivity implements View.OnClickListener {
    private EditText around_activity_edTv;
    private TextView activity_around_bacBtn, activity_around_saveBtn;
    private ImageView around_img_Iv;
    private byte[] data;
    private Bitmap bitmap;
    private String wayKey;
    private String picturePath;//系统相册的地址,由ChoseActivity传过来的
    private String note;//editText获取的字符串*(数据库)

    private String time;//照片时间戳

    private String pictureKey;//图片索引,用于保存数据库,之后调取图片用(数据库)
    private int month;//月(数据库)
    private int date;//日(数据库)

    private AroundHelper aroundHelper;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_around);

        initView();
        initTime();
        initData();

    }

    private void initTime() {
        Time t = new Time(); // or Time t=new Time("GMT+8"); 加上Time Zone资料
        t.setToNow(); // 取得系统时间。
        month = t.month + 1;
        Toast.makeText(this, month+"月",Toast.LENGTH_SHORT).show();
        date = t.monthDay;
    }

    private void initData() {
        aroundHelper = new AroundHelper();
        wayKey = getIntent().getStringExtra("wayKey");
        if (wayKey.equals("0")) {
            data = getIntent().getByteArrayExtra("bitmap");
            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);

            bitmap = adjustPhotoRotation(bitmap, 90);
//            Log.i("shaco", bitmap + "**************");

            around_img_Iv.setImageBitmap(bitmap);

        } else if (wayKey.equals("1")) {
            picturePath = getIntent().getStringExtra("picturePath");
            around_img_Iv.setImageBitmap(BitmapFactory.decodeFile(picturePath));
            Log.i("shaco", (BitmapFactory.decodeFile(picturePath)) + "**************");
        }

    }

    private void initView() {
        around_activity_edTv = (EditText) findViewById(R.id.around_activity_edTv);

        activity_around_bacBtn = (TextView) findViewById(R.id.activity_around_bacBtn);
        activity_around_saveBtn = (TextView) findViewById(R.id.activity_around_saveBtn);
        around_img_Iv = (ImageView) findViewById(R.id.around_img_Iv);
        activity_around_bacBtn.setOnClickListener(this);
        activity_around_saveBtn.setOnClickListener(this);
    }

    /**
     * 第二种旋转方式(旋转图片的方法)
     *
     * @param bm
     * @param orientationDegree
     * @return
     */
    Bitmap adjustPhotoRotation(Bitmap bm, final int orientationDegree) {

        Matrix m = new Matrix();
        m.setRotate(orientationDegree, (float) bm.getWidth() / 2, (float) bm.getHeight() / 2);
        float targetX, targetY;
        if (orientationDegree == 90) {
            targetX = bm.getHeight();
            targetY = 0;
        } else {
            targetX = bm.getHeight();
            targetY = bm.getWidth();
        }

        final float[] values = new float[9];
        m.getValues(values);

        float x1 = values[Matrix.MTRANS_X];
        float y1 = values[Matrix.MTRANS_Y];

        m.postTranslate(targetX - x1, targetY - y1);

        Bitmap bm1 = Bitmap.createBitmap(bm.getHeight(), bm.getWidth(), Bitmap.Config.ARGB_8888);
        Paint paint = new Paint();
        Canvas canvas = new Canvas(bm1);
        canvas.drawBitmap(bm, m, paint);

        return bm1;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activity_around_bacBtn://取消按钮

                QuitFragment quitFragment = new QuitFragment();
                quitFragment.show(getSupportFragmentManager(), "quitfragment");
                break;
            case R.id.activity_around_saveBtn:
                if (wayKey.equals("0")) {
                    saveData();
                    pictureKey = "/storage/sdcard0/searchim/" + time;
                    getEditText();
                    addDB();

                } else if (wayKey.equals("1")) {
                    pictureKey = picturePath;
                    getEditText();
                    addDB();
                }
                Intent intent = new Intent(this, NoteActivity.class);
                startActivity(intent);
                Toast.makeText(this,"保存成功",Toast.LENGTH_SHORT).show();
                finish();
                break;
        }
    }

    public void saveData() {
        String fileName = "sdcard/searchim/";
        time = String.valueOf(System.currentTimeMillis());
        File file = new File(fileName);
        if (!file.exists()) {
            file.mkdir();
        }
        savePicToSdcard(bitmap, fileName, time);

    }

    public static String savePicToSdcard(Bitmap bitmap, String path, String fileName) {
        String filePath = "";
        if (bitmap == null) {
            return filePath;
        } else {

            filePath = path + fileName;
            File destFile = new File(filePath);
            OutputStream os = null;
            try {
                os = new FileOutputStream(destFile);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
                os.flush();
                os.close();
            } catch (IOException e) {
                filePath = "";
            }
        }
        return filePath;

    }

    public void getEditText() {
        note = around_activity_edTv.getText().toString();

    }

    public void addDB() {
        List<AroundInfor> list = new ArrayList<>();
        AroundInfor aroundInfor = new AroundInfor();
        aroundInfor.setPictureKey(pictureKey);
        aroundInfor.setMonth(month);
        Toast.makeText(this, month+"月",Toast.LENGTH_SHORT).show();
        aroundInfor.setDate(date);
        aroundInfor.setNote(note);
        list.add(aroundInfor);
        aroundHelper.saveAroundInfor(list);
    }
}
